from flask import Blueprint, request, render_template, jsonify, json, session, redirect
from models import Homepage
from pymysql import cursors
from collections import OrderedDict
from exts import db
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint("homepage", __name__, url_prefix="/homepage")


@bp.before_request
def before_request():
    """公告蓝图权限检查"""
    # 检查用户是否登录
    if session.get('is_login') != 'true':
        return redirect('/login')
    
    # 获取当前请求的路径
    current_path = request.path
    user_role = session.get('role')
    
    # 检查用户角色
    if user_role not in ['teacher', 'student']:
        return jsonify({'error': '用户角色无效'}), 403
    
    # 只有教师可以创建、修改、删除公告
    if (current_path.startswith('/homepage/save') or 
        current_path.startswith('/homepage/update') or 
        current_path.startswith('/homepage/delete')):
        if user_role != 'teacher':
            return jsonify({'error': '权限不足，仅教师可以管理公告'}), 403


@bp.route("/")
def student_index():
    return "这是公告界面"


@bp.route("/list1", methods=["GET"])
def homepage_list1():
    # 1。get查找 根据主键查找
    # teacher = Teacher.query.get(1001)
    # print(teacher.name)
    # 2。fliter_by查找
    # students = Student.query.filter_by(class_id = "230101")
    ID = request.args.get("ID")
    if ID is not None:
        homepages = Homepage.query.filter_by(ID=ID)
    else:
        homepages = Homepage.query.all()
    out_data = []
    data = []
    i = 0
    for homepage in homepages:
        data.append(homepage.to_json())
        i += 1
    out_data.append(OrderedDict(count=i))
    out_data.append(OrderedDict(data=data))
    return OrderedDict(code=0, count=i, data=data)


@bp.route("/list")
def homepage_list():
    print("作业列表")
    # 1。get查找 根据主键查找
    # teacher = Teacher.query.get(1001)
    # print(teacher.name)
    # 2。fliter_by查找
    # students = Student.query.filter_by(class_id = "230101")
    return render_template('homepage.html')


@bp.route('/delete/<ids>', methods=["GET"])
def homepage_delete(ids):  # put application's code here
    # 再sallist中删除name的信息
    homepage = Homepage.query.filter_by(ID=ids).first()
    db.session.delete(homepage)
    db.session.commit()
    data = {'code': 0, 'msg': "成功"}

    return jsonify(data)


@bp.route('/save', methods=["POST"])
def homepage_save():  # put application's code here
    # 再sallist中修改name的信息
    data = request.json
    print(session.get("user_name"))
    homepage = Homepage(ID=data.get("ID"), headline=data.get('headline'), notice=data.get("notice"),
                        notice_time=data.get("notice_time"),
                        issuer=session.get('user_name'))
    db.session.add(homepage)
    db.session.commit()
    data = {'code': 0, 'msg': "成功"}
    return json.dumps(data)


@bp.route('/update', methods=["POST"])
def homepage__edited():  # put application's code here
    # 再sallist中修改name的信息
    data = request.json
    homepage = Homepage.query.filter_by(ID=data.get("ID")).first()
    homepage.ID = data.get("ID")
    homepage.headline = data.get("headline")
    homepage.notice = data.get("notice")
    homepage.notice_time = data.get("notice_time")
    db.session.commit()
    data = {'code': 0, 'msg': "成功"}
    return json.dumps(data)
